package com.base.cn.platform.os.service.manage.work;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.manage.work.SysUserWorkBenchDao;
import com.base.cn.platform.os.entity.manage.function.SysFunction;
import com.base.cn.platform.os.entity.manage.work.SysUserWorkBench;
import com.base.cn.platform.os.service.manage.function.SysFunctionBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工作台Biz
 *
 * @author s.li
 * @create 2018-04-13-9:32
 */
@Service
public class SysUserWorkBenchBiz extends BaseBiz<SysUserWorkBench,SysUserWorkBenchDao> {

    @Autowired
    private SysFunctionBiz sysFunctionBiz;

    /**
     * 获取用户工作台的权限列表
     * @param userId 用户ID
     * @return List<SysFunction>
     */
    public List<SysUserWorkBench> findUserWordFunctionList(BigDecimal userId){
        SysUserWorkBench bench =new SysUserWorkBench();
        bench.setUserId(userId);
        bench.setStatus(1);//查询显示的
        List<SysUserWorkBench> sysUserWorkBenchList = this.findSysUserWorkBenchList(bench);
        boolean status = false;
        //获取用户的权限列表
        List<SysFunction> userFunctionList = null;
        if(ObjectUtils.isEmpty(sysUserWorkBenchList)){
            //获取用户的权限列表
            userFunctionList = sysFunctionBiz.findUserFunctionList(userId);
            if(ObjectUtils.isNotEmpty(userFunctionList)){
                Map<Integer,List<SysFunction>> userFunctionMap = userFunctionList.stream().collect(Collectors.groupingBy(e->e.getShowIndex()));
                List<SysFunction> workFunctionList = userFunctionMap.get(2);//获取在工作台显示的
                if(ObjectUtils.isNotEmpty(workFunctionList)){
                    //生成工作台数据
                    this.genWorkFunction(workFunctionList,userId,1);
                    status = true;
                }
            }
        }
        //如果添加过，且没有查询出数据，再重新查询一次
        if(status && ObjectUtils.isEmpty(sysUserWorkBenchList)){
            sysUserWorkBenchList = this.findSysUserWorkBenchList(bench);
        }
        //如果工作权限数据不为空
        if(ObjectUtils.isNotEmpty(sysUserWorkBenchList)){
            if(ObjectUtils.isEmpty(userFunctionList)){
                //获取用户的权限列表
                userFunctionList = sysFunctionBiz.findUserFunctionList(userId);
            }
            //如果用户的权限没有查询，则再查询一次
            if(ObjectUtils.isNotEmpty(userFunctionList)){
                //把用户的权限转成Map
                Map<BigDecimal,SysFunction> userFunctionMaps = userFunctionList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
                //通过父级ID分组
                Map<BigDecimal,List<SysFunction>> userFunctionListMap = userFunctionList.stream().collect(Collectors.groupingBy(e->e.getParentId()));
                StringBuffer stringBuffer = new StringBuffer();
                if(ObjectUtils.isNotEmpty(userFunctionMaps)){
                    sysUserWorkBenchList.forEach(e->{
                        SysFunction sysFunction = userFunctionMaps.get(e.getFunctionId());
                        if(ObjectUtils.isNotEmpty(sysFunction)){
                            String functionUrl = sysFunction.getFunctionUrl();
                            if(StringUtils.isNotEmpty(functionUrl)){//如果权限的URL不为空
                                e.setClickUrl(functionUrl);
                            }else{//如果权限的URL空，则表示这个权限是顶层父级权限
                                //获取权限下的子级权限列表
                                List<SysFunction> childList = userFunctionListMap.get(sysFunction.getId());
                                if(ObjectUtils.isNotEmpty(childList)){//设置第一个子级权限的URL
                                    e.setClickUrl(childList.get(0).getFunctionUrl());
                                }
                            }
                        }else {
                            stringBuffer.append(e.getId()).append(",");
                        }
                        e.setSysFunction(sysFunction);
                    });
                    if(StringUtils.isNotEmpty(stringBuffer.toString())){
                        String ids = StringUtils.subHeadTailString(stringBuffer.toString(),",");
                        SysUserWorkBench workBench = new SysUserWorkBench();
                        workBench.setStatus(2);
                        this.updateByWhereSql(workBench," id in("+ids+")");
                    }
                }
            }
            sysUserWorkBenchList.removeIf(e -> ObjectUtils.isEmpty(e.getSysFunction()));
        }
        return sysUserWorkBenchList;
    }

    /**
     * 修改工作台权限排序
     * @param userId 用户ID
     * @param paramsList 数据列表
     */
    public void updateWorkFunctionSort(BigDecimal userId,List<SysUserWorkBench> paramsList) {
        if(ObjectUtils.isNotEmpty(paramsList)){
            String ids = paramsList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
            List<SysUserWorkBench> sysUserWorkBenchList = this.find(" id in ("+ids+")",null,null);
            if(ObjectUtils.isNotEmpty(sysUserWorkBenchList)){
                Map<BigDecimal,SysUserWorkBench> sysUserWorkBenchMap = paramsList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
                sysUserWorkBenchList.forEach(e->{
                    SysUserWorkBench bench = sysUserWorkBenchMap.get(e.getId());
                    if(ObjectUtils.isNotEmpty(bench)){
                        e.setSort(bench.getSort());
                    }
                    e.setUserId(userId);
                });
                this.updateBatch(sysUserWorkBenchList);
            }
        }
    }

    /**
     * 获取未显示在工作上的权限列表
     * @param type 类型 provider运营支持，operate内容提供，prepare系统准备
     * @param userId 用户ID
     * @return 权限列表
     */
    public List<SysFunction> queryNotShowFunction(String type,BigDecimal userId) {
        SysUserWorkBench bench =new SysUserWorkBench();
        bench.setUserId(userId);
        //查询用户的所有工作台权限
        List<SysUserWorkBench> sysUserWorkBenchList = this.findSysUserWorkBenchList(bench);
        //获取用户的权限列表
        List<SysFunction> userFunctionList = sysFunctionBiz.findUserFunctionList(userId);
        if(ObjectUtils.isNotEmpty(sysUserWorkBenchList)){
            String functionIds = sysUserWorkBenchList.stream().map(e->e.getFunctionId().toString()).collect(Collectors.joining(",",",",","));
            if(ObjectUtils.isNotEmpty(userFunctionList)){
                //分组用户权限
                Map<Integer,List<SysFunction>> userFunctionMap = userFunctionList.stream().collect(Collectors.groupingBy(e->e.getShowIndex()));
                List<SysFunction> workFunctionList = userFunctionMap.get(2);//获取在工作台显示的
                if(ObjectUtils.isNotEmpty(workFunctionList)){
                    List<SysFunction> notGenList = new ArrayList<>();
                    workFunctionList.forEach(e->{
                        //判断是否生成过,这里只获取未生成过的
                        if(!functionIds.contains(","+e.getId().toString()+",")){
                            notGenList.add(e);
                        }
                    });
                    if(ObjectUtils.isNotEmpty(notGenList)){
                        //生成工作台数据记录，且设置默认状态是不显示的
                        this.genWorkFunction(notGenList,userId,2);
                    }
                }
            }
        }
        //只查询未显示的权限记录
        //bench.setStatus(2);
        sysUserWorkBenchList = this.findSysUserWorkBenchList(bench);
        if(ObjectUtils.isNotEmpty(sysUserWorkBenchList) && ObjectUtils.isNotEmpty(userFunctionList)){
            List<SysFunction> sysFunctionList = new ArrayList<>();
            Map<BigDecimal,SysFunction> sysFunctionMap = userFunctionList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
            int _workType = 0;
            if(type.equals("prepare")){//3系统准备
                _workType =3;
            }else if(type.equals("provider")){//1运营支持
                _workType =1;
            }else if(type.equals("operate")){//2内容提供
                _workType =2;
            }else{
                return null;
            }
            int workType = _workType;
            sysUserWorkBenchList.forEach(e->{
                SysFunction sysFunction = sysFunctionMap.get(e.getFunctionId());
                if(ObjectUtils.isNotEmpty(sysFunction) && sysFunction.getWorkType().intValue()==workType){
                    SysUserWorkBench sysUserWorkBench = new SysUserWorkBench();
                    sysUserWorkBench.setUserId(userId);
                    sysUserWorkBench.setFunctionId(e.getFunctionId());
                    List<SysUserWorkBench> _sysUserWorkBenchList = this.findSysUserWorkBenchList(sysUserWorkBench);
                    sysFunction.setSysUserWorkBench(_sysUserWorkBenchList);
                    sysFunctionList.add(sysFunction);
                }
            });
            if(ObjectUtils.isNotEmpty(sysFunctionList)){
                return sysFunctionList;
            }
        }
        return null;
    }

    /**
     * 添加工作台权限显示
     * @param userId 用户ID
     * @param functionIds 显示的权限ID串
     * @param unSelectedIds 不显示的权限ID串
     */
    public void addUserWorkFunction(BigDecimal userId, String functionIds,String unSelectedIds) {
        SysUserWorkBench bench = new SysUserWorkBench();
        bench.setStatus(1);
        this.updateByWhereSql(bench," userId="+userId+" and functionId in ("+functionIds+")");
        if (StringUtils.isNotEmpty(unSelectedIds)){
            bench.setStatus(2);
            this.updateByWhereSql(bench," userId="+ userId + " and functionId in("+unSelectedIds+")");
        }
    }
    /**
     * 多条件查询工作台数据
     * @param bench 查询数据
     * @return List<SysUserWorkBench>
     */
    private List<SysUserWorkBench> findSysUserWorkBenchList(SysUserWorkBench bench){
        StringBuilder whereSql= new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(bench)){
            if(DataUtil.idIsNotNull(bench.getUserId())){
                whereSql .append(" and userId = ").append(bench.getUserId());
            }
            if(ObjectUtils.isNotEmpty(bench.getStatus()) && bench.getStatus().intValue()>0){
                whereSql .append(" and status = ").append(bench.getStatus());
            }
            if (DataUtil.idIsNotNull(bench.getFunctionId())){
                whereSql .append( " and functionId = ").append( bench.getFunctionId());
            }
        }
        whereSql .append(" order by sort asc");
        return this.find(whereSql.toString(),null,null);
    }

    /**
     * 生成工作台数据记录
     * @param sysFunctionList 权限列表
     * @param userId 用户ID
     * @param status 显示状态，1显示，2不显示
     */
    @Transactional(rollbackFor = IllegalArgumentException.class )
    private void genWorkFunction(List<SysFunction> sysFunctionList,BigDecimal userId,int status){
        if(ObjectUtils.isNotEmpty(sysFunctionList)){
            List<SysUserWorkBench> sysUserWorkBenchList = new ArrayList<>();
            sysFunctionList.forEach(e->{
                SysUserWorkBench bench = new SysUserWorkBench();
                bench.setUserId(userId);
                bench.setFunctionId(e.getId());
                bench.setStatus(status);//设置状态
                sysUserWorkBenchList.add(bench);
            });
            this.batchSave(sysUserWorkBenchList);
        }
    }
}
